# tcam-capture completion                             -*- shell-script -*-

# Copyright 2018 The Imaging Source Europe GmbH
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


_tcam-capture () {

    local cur prev words cword
    _init_completion || return

    local COMMANDS=(
        "--help"
        "-h"
        "--reset"
        "-v"
        "-vv"
        "-vvv"
        "-vvvv"
        "-vvvvv"
        "--serial"
        "--format"
        "--fullscreen"
    )
    # helper function
    # tries to find the current serial number in the existing arguments
    find_serial () {

        local next_is_serial=0

        for i in "${COMP_WORDS[@]}";
        do
            if [ $next_is_serial -eq 1 ]; then
                echo $i
                break
                # return $i
            fi
            if [ "$i" = "--serial" ]; then
                next_is_serial=1
            fi
        done
    }

    case $prev in
        --serial)
            COMPREPLY=( $( compgen -W "$( tcam-ctrl -l | awk -print 'NF>1{print $4}' )" -- "$cur" ) )
            return 0
            ;;
        --format)

            local serial=$(find_serial)

            if [ -z $serial ]; then
                # echo "Please give a serial with --serial first"
                COMPREPLY=()
            else
                COMPREPLY=( $( compgen -o noquote -W "$( tcam-ctrl -c $serial | awk '{if (NR!=1) {print}}' | awk '{gsub( ";","" ); print}' )" -- "$cur" ) )
            fi

            return 0
            ;;
    esac

    # complete using basic options
    COMPREPLY=( $( compgen -W '-h --help --reset --serial --format -v --fullscreen' -- "$cur" ) )


    if [[ ${#COMPREPLY[@]} -ne 0 ]]; then
        # this removes any options from the list of completions that have
        # already been specified somewhere on the command line, as long as
        # these options can only be used once (in a word, "options", in
        # opposition to "tests" and "actions", as in the find(1) manpage).
        local -A onlyonce=( [--serial]=1 [--format]=1 [--help]=1 [-h]=1
                            [--reset]=1 [-fullscreen]=1 )
        local j
        for i in "${words[@]}"; do
            [[ $i && ${onlyonce[$i]} ]] || continue
            for j in ${!COMPREPLY[@]}; do
                [[ ${COMPREPLY[j]} == $i ]] && unset 'COMPREPLY[j]'
            done
        done
    fi

    return 0
} &&
    complete -F _tcam-capture tcam-capture
